package hot100;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class Solution347 {
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int x : nums) {
            Integer i = map.getOrDefault(x, 0);
            i++;
            map.put(x, i);
        }
        PriorityQueue<int[]> queue = new PriorityQueue<>((o1, o2) ->  {
                return o2[0] - o1[0];
        });
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            queue.add(new int[]{entry.getValue(), entry.getKey()});
        }
        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            res[i] = queue.poll()[1];
        }
        return res;
    }
}
